package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.model.Banner;
import cn.ncu.wechat.service.BannerService;
import cn.ncu.wechat.dao.BannerMapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 
* @description 针对表【banner(轮播图表)】的数据库操作Service实现
* @createDate 2025-01-07 16:05:53
*/
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner>
    implements BannerService{

    // 假设这是你的MyBatis-Plus服务类中的一个方法
    private Integer selectMaxSort() {
        // 创建QueryWrapper并指定要查询的字段
        QueryWrapper<Banner> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("MAX(sort) AS maxSort");

        // 执行查询，返回最大值
        return getObj(queryWrapper, result -> (Integer) result);
    }

    private Long selectCountByStatus(int status) {
        QueryWrapper<Banner> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", status);
        return getBaseMapper().selectCount(queryWrapper);
    }


    @Override
    public Result addBanner(Map<String, Object> request) {
        String title = (String)request.get("title");
        String image = (String)request.get("image");
        Integer status = request.get("status") != null ? (Integer) request.get("status") : null;
        Integer sort = Optional.ofNullable(request.get("sort"))
                .map(Object::toString)
                .filter(s -> !s.trim().isEmpty())
                .map(s -> {
                    try {
                        return Integer.valueOf(s);
                    } catch (NumberFormatException e) {
                        return null;
                    }
                })
                .orElseGet(() -> {
                    // 如果sort没有传入或者转换失败，则获取最大sort值并加1
                    Integer maxSort = selectMaxSort();
                    return maxSort == null ? 1 : maxSort + 1;
                });
        Date startTime = Optional.ofNullable(request.get("startTime"))
                .map(Object::toString)
                .filter(s -> !s.trim().isEmpty())
                .map(s -> {
                    try {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        return dateFormat.parse(s);
                    } catch (Exception e) {
                        return null;
                    }
                })
                .orElse(null);

        Date endTime = Optional.ofNullable(request.get("endTime"))
                .map(Object::toString)
                .filter(s -> !s.trim().isEmpty())
                .map(s -> {
                    try {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        return dateFormat.parse(s);
                    } catch (Exception e) {
                        return null; // 或者抛出一个自定义异常
                    }
                })
                .orElse(null);
        Object linkObj = request.get("link");

        if (!(linkObj instanceof Map)) {
            return Result.error(400, "link参数格式错误");
        }

        @SuppressWarnings("unchecked")
        Map<String, Object> link = (Map<String, Object>) linkObj;
        String linkType = String.valueOf(link.get("type"));
        String linkTarget = String.valueOf(link.get("target"));

        if (StringUtils.isBlank(title) || StringUtils.isBlank(image) || status == null || link == null) {
            return Result.error(400, "缺少必要参数");
        }

        if (status != 1 && status != 2) {
            return Result.error(400, "状态值只能是1或2");
        }

        if (StringUtils.isBlank(linkType) || StringUtils.isBlank(linkTarget)) {
            return Result.error(400, "链接参数错误");
        }

        Banner banner = new Banner();
        banner.setTitle(title);
        banner.setImage(image);
        banner.setLinkType(linkType);
        banner.setLinkTarget(linkTarget);
        banner.setSort(sort);
        banner.setStatus(status);
        banner.setCreateTime(startTime);
        banner.setEndTime(endTime);

        boolean success = save(banner);

        if (success) {
            return Result.success();
        } else {
            return Result.error(500, "添加失败");
        }
    }

    @Override
    public Result getBannerList(Integer page, Integer pageSize, Integer status) {
        if(status == -1) {
            status = null;
        }
        try {
            Page<Banner> pageParam = new Page<>(page, pageSize);
            LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
            if (status != null) {
                queryWrapper.eq(Banner::getStatus, status);
            }
            queryWrapper.orderByAsc(Banner::getSort)
                    .orderByDesc(Banner::getCreateTime);
            Page<Banner> pageResult = page(pageParam, queryWrapper);
            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.error(500, "获取列表失败");
        }

    }

    @Override
    public Result updateBanner(Long id, Map<String, Object> request) {
        try {
            String title = (String)request.get("title");
            String image = (String)request.get("image");
            Integer status = request.get("status") != null ? (Integer) request.get("status") : null;
            Integer sort = Optional.ofNullable((Integer)request.get("sort"))
                    .map(Object::toString)
                    .filter(s -> !s.trim().isEmpty())
                    .map(s -> {
                        try {
                            return Integer.valueOf(s);
                        } catch (NumberFormatException e) {
                            return null;
                        }
                    })
                    .orElse(null);
            Date startTime = Optional.ofNullable(request.get("startTime"))
                    .map(Object::toString)
                    .filter(s -> !s.trim().isEmpty())
                    .map(s -> {
                        try {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            return dateFormat.parse(s);
                        } catch (Exception e) {
                            return null;
                        }
                    })
                    .orElse(null);

            Date endTime = Optional.ofNullable(request.get("endTime"))
                    .map(Object::toString)
                    .filter(s -> !s.trim().isEmpty())
                    .map(s -> {
                        try {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            return dateFormat.parse(s);
                        } catch (Exception e) {
                            return null; // 或者抛出一个自定义异常
                        }
                    })
                    .orElse(null);
            Object linkObj = request.get("link");

            if (!(linkObj instanceof Map)) {
                return Result.error(400, "link参数格式错误");
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> link = (Map<String, Object>) linkObj;
            String linkType = String.valueOf(link.get("type"));
            String linkTarget = String.valueOf(link.get("target"));

            if (StringUtils.isBlank(title) || StringUtils.isBlank(image) || status == null || link == null) {
                return Result.error(400, "缺少必要参数");
            }

            if (status != 1 && status != 2) {
                return Result.error(400, "状态值只能是1或2");
            }

            if (StringUtils.isBlank(linkType) || StringUtils.isBlank(linkTarget)) {
                return Result.error(400, "链接参数错误");
            }
            Banner existBanner = getById(id);

            if (existBanner == null) {
                return Result.error(404, "轮播图不存在");
            }

            Banner banner = new Banner();
            banner.setId(id);
            banner.setTitle(title);
            banner.setImage(image);
            banner.setLinkType(linkType);
            banner.setLinkTarget(linkTarget);
            banner.setSort(sort);
            banner.setStatus(status);
            banner.setCreateTime(startTime);
            banner.setEndTime(endTime);

            boolean updated = updateById(banner);

            if (updated) {
                return Result.success();
            } else {
                return Result.error(500, "添加失败");
            }
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @Override
    public Result deleteBanner(Long id) {
        try {
            Banner existBanner = getById(id);
            if (existBanner == null) {
                return Result.error(404,"找不到对应轮播图");
            }
            else {
                boolean delete = removeById(id);
                if(!delete){
                    return Result.error(500,"删除失败");
                }
            }
            return Result.success();
        } catch (Exception e){
            return Result.error(500,"删除失败");
        }
    }

    @Override
    public Result sortBanner(Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        Integer sort = 0;
        Banner banner = new Banner();
        if (ids != null) {
            for (Long id : ids) {
                Banner existBanner = getById(id);
                if (existBanner == null) {
                    return Result.error(404,"找不到对应轮播图");
                }
                banner.setId(id);
                banner.setSort(sort);
                ++sort;
                boolean updated = updateById(banner);
                if (!updated) {
                    return Result.error(500, "添加失败");
                }
            }
            return Result.success();
        }
        return Result.error(400, "ids列表为空");
    }

    @Override
    public Result changeStatus(Long id, Integer status) {
        try {
            Banner existBanner = getById(id);
            if (existBanner == null) {
                return Result.error(404,"找不到对应轮播图");
            }
            if (status.equals(existBanner.getStatus())) {
                return Result.success("状态未改变");
            }
            Banner banner = new Banner();
            banner.setId(id);
            banner.setStatus(status);
            boolean updated = updateById(banner);
            if (!updated) {
                return Result.error(500, "更新失败");
            }
            return Result.success();
        } catch (Exception e){
            return Result.error(500,"删除失败");
        }
    }

    @Override
    public Result deleteBanners(Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        if (ids != null) {
            for (Long id : ids) {
                try {
                    Banner existBanner = getById(id);
                    if (existBanner == null) {
                        return Result.error(404,"找不到对应轮播图");
                    }
                    else {
                        boolean delete = removeById(id);
                        if(!delete){
                            return Result.error(500,"删除失败");
                        }
                    }
                } catch (Exception e){
                    return Result.error(500,"删除失败");
                }
            }
            return Result.success();
        }
        return Result.error(400,"id列表为空");
    }

    @Override
    public Result getStatistics() {
        Map<String, Long> statusCounts = new HashMap<>();

        Long total_count = count();
        statusCounts.put("total", total_count);
        // 获取status为1的Banner记录数量
        Long countStatus1 = selectCountByStatus(1);
        statusCounts.put("activeCount", countStatus1);

        // 获取status为2的Banner记录数量
        Long countStatus2 = selectCountByStatus(2);
        statusCounts.put("inactiveCount", countStatus2);
        return Result.success(statusCounts);
    }
}




